/*
 * @Author: “ygnnli” “1585923072@qq.com”
 * @Date: 2024-08-01 23:45:39
 * @LastEditors: “ygnnli” “1585923072@qq.com”
 * @LastEditTime: 2024-08-02 11:09:31
 * @FilePath: /110/40/cp_ringqueue/Main.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "RingQueue.hpp"
#include "Thread.hpp"
#include <string>
#include <vector>
#include <unistd.h>
#include "Task.hpp"

#include <ctime>

using namespace ThreadModule;

using ringqueue_t = RingQueue<Task>;

void Consumer(ringqueue_t &rq, const std::string name)
{
    while (true)
    {
        sleep(1);
        Task t;
        rq.Pop(&t);
        std::cout << "consumer handler task: " << "[" << name << "]" << std::endl;
        t();
    }
}

void Productor(ringqueue_t &rq, const std::string name)
{
    srand(time(nullptr));
    // int cnt = 10;
    while (true)
    {

        rq.Enqueue(Dowbload);
        std::cout << "productor data: " << "[" << name << "]" << std::endl;
        // cnt--;
    }
}

void InitComm(std::vector<Thread<ringqueue_t>> *threads, int num, ringqueue_t &rq, func_t<ringqueue_t> func, const std::string &who)
{
    for (int i = 0; i < num; i++)
    {
        std::string name = "thread-" + std::to_string(i + 1) + "-" + who;
        threads->emplace_back(func, rq, name);
    }
}

void InitConsumer(std::vector<Thread<ringqueue_t>> *threads, int num, ringqueue_t &rq)
{
    InitComm(threads, num, rq, Consumer, "consumer");
}

void InitProductor(std::vector<Thread<ringqueue_t>> *threads, int num, ringqueue_t &rq)
{
    InitComm(threads, num, rq, Productor, "productor");
}

void WaitAllThread(std::vector<Thread<ringqueue_t>> &threads)
{
    for (auto &thread : threads)
    {
        thread.Join();
    }
}

void StartAll(std::vector<Thread<ringqueue_t>> &threads)
{
    for (auto &thread : threads)
    {
        std::cout << "start: " << thread.name() << std::endl;
        thread.Start();
    }
}

int main()
{
    ringqueue_t *rq = new ringqueue_t(10);
    std::vector<Thread<ringqueue_t>> threads;

    InitProductor(&threads, 1, *rq);
    InitConsumer(&threads, 1, *rq);

    StartAll(threads);

    WaitAllThread(threads);

    return 0;
}